﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bouyomichan
{
    public sealed class BouyomichanSynthesizer:IDisposable
    {
        

        public event Func<string> GetBouyomichanPath;

        public BouyomichanSynthesizer()
        {

            GetBouyomichanPath = null;
        }

        public void Send(string message)
        {

            if (_canSendable())
            {
                using (var client = new BouyomichanTcpClient())
                {

                    client.Connect();
                    client.Send(message);
                }
            }
            
        }

        private bool _canSendable()
        {
            var bouyomichanPath = _getBouyomichanPath();
            var processes = _getBouyomichanProcess();
            if (processes.Length <= 0)
            {
                
                
                

                if (bouyomichanPath != null && File.Exists(bouyomichanPath))
                {
                    var bouyomichanProcess = Process.Start(bouyomichanPath);
                    bouyomichanProcess.WaitForExit(5000);
                    return bouyomichanProcess != null;
                }
                else
                {
                    return false;
                }

            }
            else
            {
                return true;
            }
        }

        private string _getBouyomichanPath()
        {
            if (GetBouyomichanPath != null) return GetBouyomichanPath();
            else return null;
        }

        private Process[] _getBouyomichanProcess()
        {
            return Process.GetProcessesByName("Bouyomichan");
           
        }

        public void Dispose()
        {

        }
    }
}
